/*
 * SaleReturn2.java
 *
 * Created on April 1, 2007, 12:32 PM
 */

package edu.byu.isys413.jjenkins.view;

import edu.byu.isys413.jjenkins.data.ConnectionPoolException;
import edu.byu.isys413.jjenkins.data.CustomerBO;
import edu.byu.isys413.jjenkins.data.DataException;
import edu.byu.isys413.jjenkins.data.TransactionBO;
import edu.byu.isys413.jjenkins.data.TransactionDAO;
import edu.byu.isys413.jjenkins.data.TransactionLineBO;
import edu.byu.isys413.jjenkins.data.TransactionLineDAO;
import java.sql.Date;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *Processes the return of a sale transaction, and populates the view for the clerk
 * @author  Rick
 */
public class SaleReturn2 extends javax.swing.JFrame {
    private static SaleReturn2 instance = null;
    private CustomerBO cust;
    private TransactionBO original;
    private TransactionBO transreturn;
    DefaultListModel model = new DefaultListModel();
    List<TransactionLineBO> li;
    
    
    public static synchronized SaleReturn2 getInstance() {
        
        if (instance == null) {
            instance = new SaleReturn2();
        }
        
        
        return instance;
    }
    /** Creates new form SaleReturn2 */
    public SaleReturn2() {
        initComponents();
        lstLines.setModel(model);
        this.setLocationRelativeTo(null);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstLines = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        back = new javax.swing.JButton();
        next = new javax.swing.JButton();
        transId = new javax.swing.JLabel();
        date = new javax.swing.JLabel();
        return1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Items On Transaction");
        setMinimumSize(new java.awt.Dimension(1000, 300));
        jPanel1.setPreferredSize(new java.awt.Dimension(1000, 200));
        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("Items On Transaction"));
        lstLines.setBackground(new java.awt.Color(224, 223, 227));
        jScrollPane1.setViewportView(lstLines);

        jLabel1.setText("Transaction ID");

        jLabel2.setText("Date");

        back.setText("Back");
        back.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backActionPerformed(evt);
            }
        });

        next.setText("Next");
        next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextActionPerformed(evt);
            }
        });

        transId.setPreferredSize(new java.awt.Dimension(50, 14));

        date.setPreferredSize(new java.awt.Dimension(50, 14));

        return1.setText("Return");
        return1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                return1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 585, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(transId, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(55, 55, 55))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(242, 242, 242))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(388, Short.MAX_VALUE)
                .addComponent(return1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(back)
                .addGap(6, 6, 6)
                .addComponent(next)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(transId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(72, 72, 72)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(back)
                    .addComponent(next)
                    .addComponent(return1)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 585, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void return1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_return1ActionPerformed
        
// TODO add your handling code here:
        // removes transaction
        TransactionLineBO test = (TransactionLineBO)li.get(lstLines.getSelectedIndex());
        try{
            TransactionLineBO selectedline = TransactionLineDAO.getInstance().create();
            if(test.getStatus().equals("normal")){
                try{
                    //trans.removeTransactionLine(li.get(lstLines.getSelectedIndex()).getId());
                    
                    selectedline = li.get(lstLines.getSelectedIndex());
                    selectedline.setStatus("returning");
                    
                    transreturn.addTransactionLine(selectedline);
                    
                    
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if (test.getStatus().equals("returning")){
                //li.get(lstLines.getSelectedIndex()).setStatus("normal");
                selectedline = li.get(lstLines.getSelectedIndex());
                selectedline.setStatus("normal");
                
                transreturn.removeTransactionLine(li.get(lstLines.getSelectedIndex()).getId());
                
                
            }else if (test.getStatus().equals("returned")){
                JOptionPane.showMessageDialog(null,"This item has already been returned, and as such cannot be returned again");
            }
        }catch (Exception exce){
            exce.printStackTrace();
        }
        
        // repopulates the list..how to make it so the button changes text or whatever?
        populateTransactionLines();
        
        
        
    }//GEN-LAST:event_return1ActionPerformed
    
    private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
// TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_backActionPerformed
    
    private void nextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextActionPerformed
// TODO add your handling code here:
        transreturn.setDate(new Date(System.currentTimeMillis()));
        double stotal = transreturn.getSubtotal();
        stotal = 0-stotal;
        transreturn.setSubtotal(stotal);
        System.out.println("stotal "+stotal+", ttotal "+transreturn.getSubtotal());
        NewOrder.getInstance().loadForm(cust, transreturn);
        
    }//GEN-LAST:event_nextActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SaleReturn2().setVisible(true);
            }
        });
    }
    
    public void loadForm(TransactionBO transaction, CustomerBO cust) {
        try {
            this.cust = cust;
            System.out.println("starting loadform in sale2!");
            transreturn = TransactionDAO.getInstance().create();
            //original = TransactionDAO.getInstance().read(transid);//i think this negates all the extra methods
            //that i made in translineDAO...oh well it works...
            original = transaction;
            transreturn.setOriginalTrans(original);
            transreturn.setType("return");
            transId.setText(original.getId());
            date.setText(original.getDate().toString());
            
            //this should be in populate lines
            
            //now populate the jlist with all the transaction lines, showing description, quantity, price and a little return link
            //when they click on a link, then
            //transreturn.addTransactionLine(whatever they clicked on)
            //then change link to read "returned"
            //when they click on "next" do next actionperformed
            //now on newOrder, do i need to do something special if ttype is return?  i think so, because otherwise
            //it will be charging them the regular price once again.
            //also, tline should have a status variable...
            //or should i just set the whole transaction to "returned"? then make it so they can pull up the next transaction
            //and they have to compare individual translines to see extactly what was returned.
            //or is all this crap just scope creep?
            //maybe it's fine with just setting the transaction status to returned and leaving it at that
            populateTransactionLines();
            
        } catch (DataException ex) {
            ex.printStackTrace();
        }
        this.setVisible(true);
    }
    
    
    public void populateTransactionLines(){
        try{
            NumberFormat currency = NumberFormat.getCurrencyInstance();
//            trans.endTransaction();
//            lblSubTotal.setText(currency.format(trans.getSubtotal()));
//            lblTax.setText(currency.format(trans.getTax()));
//            lblTotal.setText(currency.format(trans.getTotal()));
            model.removeAllElements();
            
            
            // List of all transactionlines
            //li = TransactionLineDAO.getInstance().readByTransaction(original.getId());
            li =  original.getTransactionList();
            
            
            // creaetes entries
            for(int i = 0; i < li.size(); i++){
                TransactionLineBO line =li.get(i);
                String description = "-";
                String quan = "-";
                String coupon = "-";
                String status = "-";
                
                //checks to see if there is a revenue source
                description = line.getRevenueSource().getDescription();
                status = line.getStatus();
                quan = line.getRevenueSource().getQuantity() + "";
                double price = line.getSubtotal();
                
                
                // This add space onto the description to have uniform formatting
                while(description.length()<35){
                    description += " ";
                }
                
                //checks to see if there is a coupon
                if(line.getCouponID() != null){
                    coupon = currency.format(line.getCoupon().getAmount());
                }
                
                String strLine  =description + "           quantity:  " + quan +   "        coupon:  " + coupon + "         price:  " + currency.format(price)+"           status:  "+status;
                
                model.addElement(strLine);
                
                this.setVisible(true);
            }
        }catch(DataException ex){
            JOptionPane.showMessageDialog(null,ex.toString(),"Error adding item to View", JOptionPane.ERROR_MESSAGE);
        }
        this.setVisible(true);
        
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton back;
    private javax.swing.JLabel date;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lstLines;
    private javax.swing.JButton next;
    private javax.swing.JButton return1;
    private javax.swing.JLabel transId;
    // End of variables declaration//GEN-END:variables
    
}
